<template>
  <div id="personal_page">
    <div v-if="!userObj.id">
      <h1 class="un_login_h1">未登录</h1>
      <el-button type="primary" class="go_login_btn" @click="$router.push('/login')">前往登录</el-button>
    </div>
    <div v-else>
      <div class="personal_mask"></div>
      <personal-head :user-img="userObj.userPortrait"/>
      <h2 style="text-align: center;background: #ffffff;line-height: 50px;">修改个人信息</h2>
      <div class="personal_page_body">
        <div class="personal_body_left">
          <div class="left_bodyitem">
            <img :src="userObj.userPortrait"/>
            <div class="personal_username">用户名:{{userObj.username}}</div>
          </div>
        </div>
        <div class="personal_body_right">
          <el-form ref="form" :model="userObj" label-width="80px">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="userObj.nickname"></el-input>
            </el-form-item>
            <!--          <el-form-item label="真实姓名" prop="realName">-->
            <!--            <el-input v-model="userObj.realName"></el-input>-->
            <!--          </el-form-item>-->
            <el-form-item label="密码" prop="realName">
              <el-input v-model="userObj.password" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码"  prop="passwordAgain">
              <el-input v-model="userObj.passwordAgain" show-password @blur="determinePassword"/>
            </el-form-item>
            <el-form-item label="性别">
              <el-radio v-model="userObj.userKind" :label="0">男</el-radio>
              <el-radio v-model="userObj.userKind" :label="1">女</el-radio>
            </el-form-item>
            <el-form-item label="更新头像" >
              <el-upload
                  class="avatar-uploader"
                  :action="`${baseurl}/api/imgupload`"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
              >
                <img  v-if="userObj.userPortrait" :src="userObj.userPortrait" class="avatar">
                <i style="border: 1px dashed #ffff" v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button @click="centerDialogVisible=true">查看个人购买记录</el-button>
              <el-button type="primary" @click="updateuser">修改信息</el-button>
              <el-button @click="goHome" type="success">返回首页</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>


      <!--  个人购买历史  -->
      <el-dialog
          title="个人购买历史"
          :visible.sync="centerDialogVisible"
          width="70%"
          center>
        <div class="user_borrows">
          <ul  class="borrow_items">
            <li v-for="(item,index) of borrowList" :key="item._id">
              {{index+1}}
              <div class="borrow_items_bookname">《{{item.name}}》</div>
              <div class="borrow_items_author">图书作者： {{item.author}}</div>
              <div class="borrow_items_author">出版社： {{item.press}}</div>
              <!--            <div class="borrow_items_time">借阅时间： {{item.startTime}}</div>-->
            </li>
          </ul>
        </div>
        <el-button class="borrow_btn" @click="centerDialogVisible = false">确定</el-button>
      </el-dialog>

    </div>

  </div>
</template>

<script>
import baseurl from "../const/baseurl";
import PersonalHead from "../components/PersonalHead";
import {getUserById,updateUser,getBorrowByUserId,getBookByIsbn} from "../network/home";
// import {dateFormat} from "../utils/date";
//

export default {
  name: "PersonalPage",
  components: {PersonalHead},
  data(){
    return{
      userObj:{
        id:"",
        nickname:'',
        username: '',
        password: '',
        userKind: 0,
        adminIcon: '',
        userPortrait: '',
        passwordAgain: '',
      },
      imageUrl: '',
      baseurl,
      borrowList:[],
      centerDialogVisible:false,//是否显示对话框
    }
  },
  methods:{
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(file);
      // console.log(this.imageUrl);
      console.log(res);
      if (res.state==="success"){
        this.userObj.userPortrait=res.img.imgUrl;
      }
      console.log(this.userObj.userPortrait);
    },
    beforeAvatarUpload() {//file
    },
    //判断密码和确认密码是否相同
    determinePassword(){
      if (this.userObj.password === this.userObj.passwordAgain){
        console.log('两次密码相同');
      }else{
        if (this.userObj.passwordAgain){
          console.log("两次密码不同");
          this.$notify.error({
            title: '两次密码不一致',
            message: '两次输入的密码不一致,请检查',
            duration: 5000,
            // type: 'warning',
          });
        }
      }
    },
    updateuser(){
      if (this.userObj.password === this.userObj.passwordAgain){
        updateUser(this.userObj).then((result)=>{
          console.log(result);
          this.$message({
            message: '修改成功！',
            type: 'success'
          });
          //加下来是跳转路由刷新,利用session保存当前页面的地址,
          //然后跳转到空白页,空白页再通过session中的路径跳转回来
          sessionStorage.setItem('JinBookProBlankUrl','/personal');
          this.$router.push('/blankpage');
        }).catch((reason)=>{
          console.log(reason);
        })
      }else{
        if (this.userObj.passwordAgain){
          console.log("两次密码不同");
          this.$notify.error({
            title: '两次密码不一致',
            message: '两次输入的密码不一致,请检查',
            duration: 5000,
            // type: 'warning',
          });
        }
      }

    },
    goHome(){
      this.$router.push('/home');
    }
  },
  created() {
    const userId=localStorage.getItem("JinBookProFront");
    this.userObj.id=userId;
    //根据userId获取用户数据
    getUserById(userId).then((result)=>{
      console.log(result);
      this.userObj=result.data.data;
    }).catch((reason)=>{
      console.log(reason);
    });
    //根据userName获取用户的借阅历史
      let data=[];
    getBorrowByUserId(userId).then(async (result)=>{
        data = result.data.data;
        console.log(data);
        for (let i = 0; i < data.length; i++) {
          let newBorrow={};
          // newBorrow.startTime=dateFormat(data[i].startTime);
          await getBookByIsbn(data[i].isbn).then((result)=>{
            console.log(result);
            // this.borrowList[i].bookName=result.data.data.bookName;
            newBorrow.name=result.data.data.name;
            newBorrow.author=result.data.data.author;
            newBorrow.press=result.data.data.press;
          })
          this.borrowList.push(newBorrow);
        }
      });
  },
}
</script>

<style scoped>
#personal_page{
  /*position: relative;*/
  width: 90%;
  margin: 0 auto;
}
.personal_mask{
  position: absolute;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100%;
  z-index: -1;
  background: #eeeeee;
}
.personal_page_body{
  display: flex;
  /*width: 90%;*/
  height: 600px;
  margin: 0 auto;
  background: #ffffff;
  border-radius: 10px;
}
.personal_body_left{
  position: relative;
  flex: 1;
  height: 100%;
  text-align: center;
}
.left_bodyitem{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50% ,-80%);
}
.personal_body_left img{
  width: 150px;
  height: 150px;
  border-radius: 50%;
}
.personal_body_left .personal_username{
  font-size: 20px;
  font-weight: bolder;
}
.personal_body_right{
  flex: 2;
  height: 100%;
  padding: 5px 50px;
}
.avatar{
  width: 150px;
  height: 150px;
  padding: 10px;
}
/*借阅记录部分*/
.user_borrows{
  width: 100%;
  overflow: hidden;
}
.borrow_items li{/*每个借阅的信息的样式*/
  display: flex;
  /*text-align: center;*/
  /*line-height: 35px;*/
  font-size: 16px;
  width: 100%;
  overflow: hidden;
  padding: 13px 0;
  border-bottom: 1px solid #cccccc;
}
.borrow_items li div{
  flex: 1;
  text-align: center;
}
.borrow_items li .borrow_items_bookname{
  width: 100px;
}
.borrow_btn{
  position: relative;
  width: 300px;
  height: 50px;
  left: 50%;
  transform: translateX(-55%);
  top: 13px;
}

/*未登录*/
.un_login_h1{
  text-align: center;
}
/*前往登录按钮*/
.go_login_btn{
  position: relative;
  margin: 20px auto;
  left: 50%;
  transform: translateX(-50%);
}
</style>
